//
//  ZDPlaceholderTextView.swift
//  1026SwiftSinaWeiBo
//
//  Created by Apple on 15/11/4.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class ZDPlaceholderTextView: UITextView {

    //提供属性给外界指定占位文本
    var placeholder: String? {
    
        didSet {
        
            //占位文本由外界指定  外界没有赋值就显示默认文本
            if placeholder != nil {
            
                placeholderLabel.text = placeholder
            }
            
            //占位文本的字体与textView的字体一样
            placeholderLabel.font = font
        }
    }
    
    //MARK: - 构造方法
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: CGRectZero, textContainer: textContainer)
        
        //准备UI
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 准备UI
    private func prepareUI() {
    
        //添加子控件
        addSubview(placeholderLabel)
        
        //添加约束
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: nil, offset: CGPoint(x: 5, y: 8))
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    //通知回调方法
    @objc private func textDidChange() {
    
        //textView有文本 hasText()返回值为true
        placeholderLabel.hidden = hasText()
    }
    
    //移除通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    
    //MARK: - 懒加载
    private lazy var placeholderLabel: UILabel = {
    
        let label = UILabel()
        
        //设置占位文本的颜色
        label.textColor = UIColor.lightGrayColor()
        
        //设置默认文本
        label.text = "share your enjoy..."
        
        return label
    }()
}
